﻿using System;
using System.ServiceProcess;
using System.ServiceModel;

namespace Informant.Services.Windows
{
	public partial class InformantWinService : ServiceBase
	{
		ServiceHost _aggregateServiceHost;
		InformantService _aggregateService;
		
		/// <summary>
		/// Initializes a new instance of the <see cref="InformantWinService"/> class.
		/// </summary>
		public InformantWinService()
		{
			InitializeComponent();
		}

		/// <summary>
		/// When implemented in a derived class, executes when a Start command is sent to the service by the Service Control Manager (SCM) or when the operating system starts (for a service that starts automatically). Specifies actions to take when the service starts.
		/// </summary>
		/// <param name="args">Data passed by the start command.</param>
		protected override void OnStart(String[] args)
		{
			//System.Diagnostics.Debugger.Launch();
			StartInformantService();
		}
		/// <summary>
		/// When implemented in a derived class, executes when a Stop command is sent to the service by the Service Control Manager (SCM). Specifies actions to take when a service stops running.
		/// </summary>
		protected override void OnStop()
		{
			if (_aggregateServiceHost != null)
			{
				_aggregateServiceHost.Close();
				_aggregateServiceHost = null;
			}
			if (_aggregateService != null)
			{
				_aggregateService.Dispose();
				_aggregateService = null;
			}
		}

		/// <summary>
		/// Starts the SMS service.
		/// </summary>
		private void StartInformantService()
		{
			if (_aggregateServiceHost == null
				|| _aggregateServiceHost.State != CommunicationState.Opened
				|| _aggregateServiceHost.State != CommunicationState.Opening)
			{
				try
				{
					_aggregateServiceHost = new ServiceHost(typeof(InformantService));
					_aggregateServiceHost.Open();
				}
				catch (Exception ex)
				{
					//TODO: Log error
					throw ex;
				}
			}
		}
	}
}
